package cn.share.life.module.other.excel;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;

@Slf4j
public class ExcelUtils {

    public static void main(String[] args) {
        String filePath = "C:\\Users\\Administrator\\Desktop\\mathUtils.xlsx";
        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis);
             FileOutputStream fos = new FileOutputStream(filePath)) {
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

            for (int i = 0; i < 20; i++) {
                Cell cell = sheet.getRow(i).getCell(0);
                if (cell == null) {
                    cell = sheet.getRow(i).createCell(0); // 如果单元格不存在，则创建它
                }
                cell.setCellValue(i + 20);
            }
            workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); // 重新计算所有公式

            for (int i = 0; i < 20; i++) {
                Cell cell = sheet.getRow(i).getCell(7);
                if (cell == null) {
                    cell = sheet.getRow(i).createCell(7); // 如果单元格不存在，则创建它
                }
                System.out.println("累计净现金流量现值,单元格公式: " + cell.getCellFormula());
                CellType cellType = cell.getCellType();
                System.out.println("单元格类型: " + cellType);
                double numericCellValue = cell.getNumericCellValue();
                System.out.println("累计净现金流量现值: " + numericCellValue);
            }
            workbook.write(fos); // 写入修改后的内容到文件
        } catch (Exception e) {
            log.error("Error processing Excel file: {}", e.getMessage(), e);
        }
    }
}
